package handler //业务包

import (
	"fmt"
	"log"
	"os"
	"shi_project/main/authentication"
	"shi_project/main/config"
	"shi_project/main/database"
	"shi_project/main/middle"
	"shi_project/main/utils"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

func Get(c *gin.Context) {
	type MyPermission struct {
		Id        string          `json:"id"`
		Name      string          `json:"name"`
		Type      string          `json:"type"`
		Parent_id string          `json:"parent_id"`
		Children  []*MyPermission `json:"children"`
	}
	var p MyPermission = MyPermission{}
	p.Children = []*MyPermission{}

	c.JSON(200, gin.H{
		"msg": p,
	})
	// c.Writer.Write([]byte("hello"))
	// c.String(200, string("您们好呀"))
}

func Music(c *gin.Context) {
	if config.Env == "dev" {
		data := gin.H{
			"list": []string{
				"2002年的第一场雪.mp3",
				"yujian.mp3",
				"光年之外-G.E.M.邓紫棋.320.mp3",
				"光辉岁月-Beyond.320.mp3",
				"句号-G.E.M.邓紫棋.320.mp3",
				"可能.mp3",
				"同桌的你.mp3",
				"大城小爱-王力宏.320.mp3",
				"太想念-豆包.320.mp3",
				"明天,你好(电视剧《加油吧实习生》插曲)-牛咖啡.128.mp3",
				"曾经你说.mp3",
				"月半小夜曲.mp3",
				"果汁分你一半.mp3",
				"江山更(电视剧《倚天屠龙记(马景涛版)》尾曲)-李丽芬.320.mp3",
				"独家记忆-陈小春.320.mp3",
				"痴心绝对-李圣杰.128.mp3",
				"离别开出花 - 就是南方凯（项学凯）.mp3",
				"笑纳-花僮.320.mp3",
				"粉红色的回忆-韩宝仪.320.mp3",
				"遇见.mp3",
				"雨爱.mp3",
			},
			"status":    200,
			"totalSize": "183.07MB",
		}
		c.JSON(200, data)
		return
	}
	demoPath := config.MUSIC
	fileArr, err := os.ReadDir(demoPath)
	if err != nil {
		c.JSON(400, gin.H{
			"status": 400,
			"msg":    err,
		})
		return
	}
	var list []string
	var totalSize int64
	for _, v := range fileArr {
		file, err := os.Stat(demoPath + "/" + v.Name())
		if err != nil {
			log.Fatalln(err)
			return
		}
		totalSize += file.Size()
		list = append(list, v.Name())
	}
	c.JSON(200, gin.H{
		"status":    200,
		"totalSize": utils.FormatFileSize(totalSize),
		"list":      list,
	})
}

func Roles(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.Character{}
	pagination := database.Pagination{}
	if name := c.Query("name"); name != "" {
		json.Name = name
	}
	if current := c.Query("current"); current != "" {
		pagination.Current = current
	}
	if pageSize := c.Query("pageSize"); pageSize != "" {
		pagination.PageSize = pageSize
	}
	msg, options, err := database.GetRolesList(json, pagination)
	if err != nil {
		c.JSON(400, gin.H{
			"code":    -1,
			"msg":     err,
			"options": options,
		})
		return
	}
	c.JSON(200, gin.H{
		"code":    0,
		"msg":     msg,
		"options": options,
	})
}
func AddRoles(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.Character{}
	c.ShouldBind(&json)
	msg, err := database.ARoles(json)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  msg,
			"code": -1,
		})
	} else {
		c.JSON(200, gin.H{
			"msg":  msg,
			"code": 0,
		})
	}
}

// 音乐上传
func Uploads(c *gin.Context) {
	form, err := c.MultipartForm()
	fmt.Println("下载下载")
	if err != nil {
		log.Fatal(err)
	}
	//通过字段名映射
	f := form.File["file"]
	//for range遍历文件
	for _, file := range f {
		name := file.Filename
		arr := strings.Split(name, ".")
		musicType := arr[len(arr)-1]
		if musicType != "mp3" {
			c.JSON(400, gin.H{
				"status": 400,
				"msg":    "文件格式不正确",
			})
			break
		} else {
			c.JSON(200, gin.H{
				"status": 200,
				"msg":    "上传成功",
			})
		}
		fmt.Println(file.Filename)
		if config.Env == "dev" {
			c.SaveUploadedFile(file, "./tmp/"+file.Filename)
		} else {
			c.SaveUploadedFile(file, config.MUSIC+file.Filename)
		}
	}
}
func DeleteRoles(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.Character{}
	c.ShouldBind(&json)
	msg, err := database.DRoles(json)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  msg,
			"code": -1,
		})
	} else {
		c.JSON(200, gin.H{
			"msg":  msg,
			"code": 0,
		})
	}
}

func PutRoles(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.Character{}
	c.ShouldBind(&json)
	msg, err := database.PRoles(json)
	if err != nil {
		c.JSON(400, gin.H{
			"code": -1,
			"msg":  msg,
		})
	} else {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  msg,
		})
	}
}
func PutPermissionList(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	p := database.PermissionContext{}
	c.ShouldBindJSON(&p)
	msg, err := database.PPermissionList(p)
	if err != nil {
		c.JSON(400, gin.H{
			"code": -1,
			"msg":  msg,
		})
	} else {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  msg,
		})
	}
}

func DeletePermissionList(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.MyPermission{}
	c.ShouldBindJSON(&json)
	n, err := database.DPermission(json)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  err,
			"code": -1,
		})
		return
	}
	c.JSON(200, gin.H{
		"msg":  n,
		"code": 0,
	})
}
func DeleteRolePermissionList(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.MyPermission{}
	c.ShouldBindJSON(&json)
	n, err := database.DRolePermission(json)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  err,
			"code": -1,
		})
		return
	}
	c.JSON(200, gin.H{
		"msg":  n,
		"code": 0,
	})
}

func Users(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	user := database.User{}
	p := database.Pagination{}
	if username := c.Query("username"); username != "" {
		user.Username = username
	}
	if current := c.Query("current"); current != "" {
		p.Current = current
	}
	if pageSize := c.Query("pageSize"); pageSize != "" {
		p.PageSize = pageSize

	}
	msg, options, _ := database.GUsers(user, p)
	c.JSON(200, gin.H{
		"code":    0,
		"msg":     msg,
		"options": options,
	})
}

func AddUser(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.User{}
	c.ShouldBind(&json)
	_, err := database.AUser(json)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  err,
			"code": -1,
		})
	} else {
		c.JSON(200, gin.H{
			"msg":  "添加成功",
			"code": 0,
		})
	}
}

func DeleteUser(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.User{}
	c.ShouldBind(&json)
	n, err := database.DUser(json)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  err,
			"code": -1,
		})
		return
	}
	c.JSON(200, gin.H{
		"msg":  n,
		"code": 0,
	})
}

func PutUser(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	user := database.User{}
	c.ShouldBindJSON(&user)
	fmt.Println("user=", user)
	msg, err := database.PUser(user)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  msg,
			"code": -1,
		})
	} else {
		c.JSON(200, gin.H{
			"msg":  "修改成功",
			"code": 0,
		})
	}

}

func Login(c *gin.Context) {
	json := make(map[string]interface{}) //注意该结构接受的内容
	c.ShouldBindJSON(&json)
	// c.BindJSON(&json)
	res, err := database.VerifyLogin(json)
	if err != nil {
		c.JSON(400, res)
	} else {
		c.Header("Authorization", res["token"])
		c.JSON(200, gin.H{
			"user":       res["id"],
			"status":     "200",
			"msg":        "登录成功",
			"loginTimes": res["loginTimes"],
		})
	}
}

func OutLogin(c *gin.Context) {
	c.JSON(200, gin.H{})
}

func CurrentUser(c *gin.Context) {
	str, _ := c.Request.Header["Authorization"]
	res, err := middle.ParseTokenGetInfo(str[0])
	id, err := strconv.ParseInt(res.ID, 10, 64)
	if err != nil {
		fmt.Println("数据转换失败")
		c.JSON(400, "数据转换失败")
		return
	}
	data, err := database.GetUserInfo(id)
	if err != nil {
		c.JSON(400, err)
		return
	}
	c.JSON(200, data)
}
func PermissionList(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	p := database.MyPermission{}
	name := c.Query("name")
	if name != "" {
		p.Name = name
	}
	data, err := database.GPermissionList(p)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  data,
			"code": -1,
		})
		return
	}
	c.JSON(200, gin.H{
		"msg":  data,
		"code": 0,
	})
}

func AddPermissionList(c *gin.Context) {
	if err := authentication.IsPass(c, authentication.PermissionPage); err != nil {
		c.JSON(200, gin.H{
			"code": -1,
			"msg":  err,
		})
		return
	}
	json := database.PermissionContext{} //注意该结构接受的内容
	c.ShouldBindJSON(&json)
	data, err := database.APermissionList(json)
	if err != nil {
		c.JSON(400, gin.H{
			"msg":  err,
			"code": -1,
		})
		return
	}
	c.JSON(200, gin.H{
		"msg":  data,
		"code": 0,
	})
}
